﻿using System.Collections.Specialized;
using System.Net;
using System.Security.Permissions;
using System.Text;
using Shinkansen.Support;

namespace Shinkansen.Web
{
    /// <summary>
    /// Custom JavaScript cruncher which utilizes Google's Closure Compiler web API
    /// </summary>
    /// <remarks>To use this cruncher, your site must run in full trust. See http://msdn.microsoft.com/en-us/library/ms998341.aspx.</remarks>
    [PermissionSet (SecurityAction.Demand, Name="FullTrust")]
    public class GoogleJsCruncher : IJsCruncher
    {
        private const string _closureCompilerUrl = "http://closure-compiler.appspot.com/compile";
        
        /// <summary>
        /// Crunches javaScript with Google's Closure Compiler
        /// </summary>
        /// <param name="content">The content.</param>
        /// <returns></returns>
        public byte[] Process (byte[] content)
        {
            using (WebClient webClient = new WebClient ())
            {
                webClient.Headers.Add ("content-type", "application/x-www-form-urlencoded");

                string textualContent = Encoding.UTF8.GetString (content);
                NameValueCollection parameters = new NameValueCollection
                {
                    { "compilation_level", "SIMPLE_OPTIMIZATIONS" },
                    { "output_format", "text" },
                    { "output_info", "compiled_code" },
                    { "js_code", textualContent }
                };

                return webClient.UploadValues (_closureCompilerUrl, parameters);
            }
        }
    }
}
